import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import ClaimListBlock from './ClaimListBlock'
import { ClaimContext, changeClaimItemFeeConfig, removeClaimItemFeeConfing, initData, formatClaim, computeItemCount } from './context'
import { Line, Cell } from '@components/ApprovePre/Approve'

function Main ({ formRef, label, name, claim }) {
  const [claimItemConfig, setClaimItemConfig] = useState([])
  const [claimItemFeeConfig, setClaimItemFeeConfig] = useState([])
  useEffect(() => {
    initData((d) => setClaimItemConfig(d.claimItemConfig))
  }, [formRef])
  useEffect(() => {
    if (claimItemConfig.length !== 0) {
      formatClaim(claimItemConfig, claim, undefined, formRef, name, setClaimItemFeeConfig)
    }
  }, [claim, claimItemConfig, formRef, name])
  const context = {
    claimItemConfig,
    claimItemFeeConfig,
    setClaimItemFeeConfig,
    changeClaimItemFeeConfig: changeClaimItemFeeConfig.bind(this, formRef, name, (d) => setClaimItemFeeConfig(d), () => {}),
    removeClaimItemFeeConfing,
    computeClaimFee: () => { computeItemCount(formRef, name, claim) }
  }
  return (
    <ClaimContext.Provider value={context}>
      <Line>
        <Cell style={{ width: '65%' }}>
          <ClaimListBlock label={label} name={name} />
        </Cell>
      </Line>
    </ClaimContext.Provider>
  )
}

Main.propTypes = {
  formRef: PropTypes.object,
  label: PropTypes.string,
  name: PropTypes.string,
  claim: PropTypes.object
}
Main.defaultProps = {
  formRef: {},
  label: '',
  name: '',
  claim: undefined
}

export default Main
